package 二分查找;

public class 二分查找 {
    public static void main(String[] args) {
        int[] list = {1,2,3,4,5,6,7,8,9,12,23,34,45,77};

        int index = binarySearch(list,77);

        if (index == -1) {
            System.out.println("查找的元素不再列表中");
        }else {
            System.out.println("查找的元素索引是:"+index);
        }
    }

    public static int binarySearch(int[] list,int i) {
        int left = 0;
        int right = list.length-1;
        int middle = right/2;

        while (left<=right) {
            if (list[middle] == i) {
                return middle;
            }else if (list[middle]<i) {
                left = middle+1;
            }else {
                right = middle-1;
            }
            middle = (left+right)/2;
        }
        return -1;
    }
}
